package cn.parllay.dingdangproject.utils;

import android.util.Log;

import java.util.concurrent.TimeUnit;

import cn.parllay.dingdangproject.client.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * Created by sunny on 2018/1/18.
 */

public class ConnectionManager {

    private int port;
    private String host;
    public SocketChannel mSocketChannel;
    private Bootstrap mBootstrap;

    public ConnectionManager(int port, String host) {
        this.port = port;
        this.host = host;
        init();
    }

    /**
     * 连接大方法
     *
     * @return
     */
    public boolean connect() {
        Log.e("TAG", "开始连接");
        try {
            ChannelFuture future = mBootstrap.connect(host, port).sync();
            future.awaitUninterruptibly();
            if (future.isSuccess()) {
                mSocketChannel = (SocketChannel) future.channel();
                SocketChanelManager.getInstance().setSocketChannel(mSocketChannel);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("TAG", "连接失败：" + e.getMessage().toString());
            return false;
        }
        return mSocketChannel == null;
    }

    /**
     * 断开连接的方法
     */
    public void disConnect() {
        mSocketChannel.disconnect();
        mSocketChannel = null;
        mBootstrap = null;
    }

    private void init() {

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        mBootstrap = new Bootstrap();
        mBootstrap.channel(NioSocketChannel.class);
        mBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        mBootstrap.group(eventLoopGroup);
        mBootstrap.remoteAddress(host, port);
        mBootstrap.handler(new DefaultChannelHandler());
    }

    public static class DefaultChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) {
            //心跳包     第一个参数 20 表示读操作空闲时间      第二个参数 10 表示写操作空闲时间    第三个参数 60*10 表示读写操作空闲时间      第四个参数 单位

                socketChannel.pipeline().addLast(new IdleStateHandler(30, 60, 100, TimeUnit.SECONDS));
                socketChannel.pipeline().addLast(new ObjectEncoder());
                socketChannel.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                socketChannel.pipeline().addLast(new NettyClientHandler());

        }
    }
}
